package com.itheima.sh.servlet;

import com.itheima.sh.tool.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/*
       historyServlet:在  goods2.html页面中点击历史记录按钮，执行该servlet，在该servlet中取出浏览器客户端的历史记录的cookie并将商品历史记录响应给浏览器。
 */
@WebServlet("/historyServlet")
public class HistoryServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //1.获取cooloe
        Cookie history = CookieUtils.getCookies(request, "history");
        //2.判断是否为空
        if (history == null){
            response.getWriter().print("<a href=\"/goods.html\">您还没有浏览记录，去浏览吧</a>");
        }else {
            //4.不等于null,说明有历史记录，取出cookie的value  galaxy_chuizi_xiaomi
            String value = history.getValue();
            //5.按照_下划线切割为数组
            String[] arr = value.split("_");
            //6.响应给浏览器
            response.getWriter().print("您浏览的商品记录是:"+ Arrays.toString(arr));
            response.getWriter().print("<br><a href=\"/goods.html\">继续浏览</a>");
        }
    }
}